package com.study;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

/**
 * @author zhuzi
 * 2023/9/18 15:22
 */
public class NoUtils {

    /**
     * 26字母+10个数字
     */
    private static final String secret = "1QAZ2WSX3EDC4RFV5TGB6YHN7UJM8IK9OL0P";

    public static void main(String[] args) {
        for (String original : Lists.newArrayList("MH9999999",
                "AN4587961",
                "CH4587961",
                "GQ4587961",
                "BC2309181")) {
            String encryStr = encry(original);
            String decryStr = decry(encryStr);
            System.out.println(StrUtil.format("加密后[{}]\n还原后[{}]\n加密前[{}]\n--------------", encryStr, decryStr, original));


        }
        System.out.println(encry("MH2300045"));
        System.out.println(decry("ZAQ1PCSNM"));
        System.out.println(decry("7B2ZACSNM"));
    }


    /**
     * 移位加密
     *
     * @param str 被加密字符串
     * @return {@link String}
     */
    public static String encry(String str) {
        str=str.trim();
        StringBuffer sb = new StringBuffer();
        char[] charArray = str.toCharArray();
        for (int j = 0; j < charArray.length; j++) {
            String s = String.valueOf(charArray[j]);
            int indexOf = StringUtils.indexOf(secret, s);
            int i = indexOf + j;
            if (i >= secret.length()) {
                i = i - secret.length();
            }
            String substring = StringUtils.substring(secret, i, i + 1);
            sb.append(substring);
        }
        return sb.reverse().toString();
    }

    /**
     * 移位解密
     *
     * @param str 被解密字符串
     * @return {@link String}
     */
    public static String decry(String str) {
        str = new StringBuffer(str.trim()).reverse().toString();
        StringBuffer sb = new StringBuffer();
        char[] charArray = str.toCharArray();
        for (int j = 0; j < charArray.length; j++) {
            String s = String.valueOf(charArray[j]);
            int i = StringUtils.indexOf(secret, s) - j;
            if (i < 0) {
                i = secret.length() + i;
            }
            String substring = StringUtils.substring(secret, i, i + 1);
            sb.append(substring);
        }
        return sb.toString();
    }
}
